import 'package:carousel_slider/carousel_slider.dart';
import 'package:extended_image/extended_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_yn_goods/config/app_color.dart';
import 'package:flutter_yn_goods/config/app_config.dart';
import 'package:flutter_yn_goods/config/app_routes.dart';
import 'package:flutter_yn_goods/config/app_theme.dart';
import 'package:flutter_yn_goods/config/app_translations.dart';
import 'package:flutter_yn_goods/generated/assets.dart';
import 'package:flutter_yn_goods/pages/model_home.dart';
import 'package:flutter_yn_goods/user/app_user_manager.dart';
import 'package:flutter_yn_goods/utils/loading/loading_utils.dart';
import 'package:flutter_yn_goods/utils/log/utils_log.dart';
import 'package:flutter_yn_goods/utils/shared/shared_export.dart';
import 'package:flutter_yn_goods/utils/utils_other.dart';
import 'package:flutter_yn_goods/widgets/image/auto_image.dart';
import 'package:flutter_yn_goods/widgets/image/image_view.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:screenshot/screenshot.dart';
import 'home_logic.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter/services.dart';

class HomePage extends StatelessWidget {
  final logic = Get.put(HomeLogic());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: AppColor.colorF6F8FB,
        body: Obx(() {
          return Column(
            children: [
              _buildAppbar(),
              Expanded(
                  child: SmartRefresher(
                      onRefresh: () {
                        // clog('2');
                        logic.page = 1;
                        logic.loadData();
                      },
                      onLoading: () {
                        clog('1');
                        logic.page++;
                        logic.loadData();
                      },
                      controller: logic.refreshController,
                      child: CustomScrollView(
                        // controller: logic.scrollController,
                        slivers: [
                          // SliverAppBar(
                          //   pinned: true,
                          //   backgroundColor: Colors.white,
                          //   // foregroundColor: Colors.white,
                          //
                          //   leading: AppUserManager().isLeader()
                          //       ? GestureDetector(
                          //           behavior: HitTestBehavior.opaque,
                          //           onTap: () {
                          //             logic.openShareAndScreenshot(0);
                          //           },
                          //           child: Container(
                          //             // color: Colors.red,
                          //             padding: EdgeInsets.only(left: 16.w),
                          //             alignment: Alignment.center,
                          //             child: Icon(
                          //               Icons.save_alt,
                          //               size: 24.w,
                          //             ),
                          //           ),
                          //         )
                          //       : _buildAppLogo(),
                          //   leadingWidth: AppUserManager().isLeader() ? 60.w : 200.w,
                          //   actions: [
                          //     _buildCopyId(),
                          //     16.horizontalSpace,
                          //   ],
                          // ),
                          SliverToBoxAdapter(
                            child: _buildCarouselSlider().marginOnly(
                                bottom: 16.w, left: 16.w, right: 16.w),
                          ),
                          // 热门推荐
                          if ((logic.homeModelRx.value.list ?? []).isNotEmpty)
                            SliverToBoxAdapter(
                              child: Container(
                                width: 1.sw,
                                padding: EdgeInsets.all(16.w),
                                color: Colors.white,
                                child: Text(
                                  LocaleKeys.hot_recommend.tr,
                                  style: TextStyle(
                                      fontSize: 16.sp,
                                      fontWeight: FontWeight.w600,
                                      color: AppColor.color282828),
                                ),
                              ),
                            ),
                          // 商品列表
                          SliverPadding(
                            padding: EdgeInsets.symmetric(horizontal: 8.w),
                            sliver: SliverGrid(
                              gridDelegate:
                                  SliverGridDelegateWithFixedCrossAxisCount(
                                      crossAxisCount: 2,
                                      mainAxisSpacing: 0,
                                      crossAxisSpacing: 0,
                                      childAspectRatio: 0.64),
                              delegate: SliverChildBuilderDelegate(
                                (BuildContext context, int index) {
                                  return GestureDetector(
                                    behavior: HitTestBehavior.opaque,
                                    onTap: () {
                                      if (AppUserManager().isLogin) {
                                        Get.toNamed(AppRoutes.goodsInfoPage,
                                            arguments: {
                                              'id': (logic.homeModelRx.value
                                                          .list ??
                                                      [])[index]
                                                  .id
                                            });
                                      } else {
                                        Get.toNamed(AppRoutes.login);
                                      }
                                    },
                                    child: Container(
                                      margin: EdgeInsets.all(8.w),
                                      decoration: BoxDecoration(
                                          color: Colors.white,
                                          borderRadius:
                                              BorderRadius.circular(8.w)),
                                      // height: 264.w,
                                      child: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          ClipRRect(
                                            borderRadius: BorderRadius.only(
                                                topLeft: Radius.circular(8.w),
                                                topRight: Radius.circular(8.w)),
                                            child: ImageView(
                                              imageUrl: (logic.homeModelRx.value
                                                          .list ??
                                                      [])[index]
                                                  .image,
                                              // imageUrl: logic.homeModel.list![index].image,
                                              width: 1.sw,
                                              height: 160.w,
                                              fit: BoxFit.cover,
                                            ),
                                          ),
                                          Container(
                                            padding: EdgeInsets.all(8.w),
                                            child: Column(
                                              crossAxisAlignment:
                                                  CrossAxisAlignment.start,
                                              children: [
                                                Text(
                                                  (logic.homeModelRx.value
                                                                  .list ??
                                                              [])[index]
                                                          .storeName ??
                                                      '',
                                                  style: TextStyle(
                                                      fontSize: 14.sp,
                                                      fontWeight:
                                                          FontWeight.w500,
                                                      color:
                                                          AppColor.color282828),
                                                  maxLines: 2,
                                                  overflow:
                                                      TextOverflow.ellipsis,
                                                ),
                                                16.verticalSpace,
                                                Row(
                                                  crossAxisAlignment:
                                                      CrossAxisAlignment.end,
                                                  children: [
                                                    Text(
                                                      UtilsOther.getGoodsPrice(
                                                          (logic.homeModelRx.value
                                                                      .list ??
                                                                  [])[index]
                                                              .price),
                                                      style: TextStyle(
                                                          fontSize: 16.sp,
                                                          fontWeight:
                                                              FontWeight.w500,
                                                          color: Colors.red),
                                                    ),
                                                    Spacer(),
                                                    Text(
                                                      LocaleKeys.sales_count.trParams({'0': (logic.homeModelRx.value.list ?? [])[index].sales.toString()}),
                                                      style: TextStyle(
                                                          fontSize: 12.sp,
                                                          color: AppColor
                                                              .color999999),
                                                    ),
                                                  ],
                                                )
                                              ],
                                            ),
                                          )
                                        ],
                                      ),
                                    ),
                                  );
                                },
                                childCount:
                                    (logic.homeModelRx.value.list ?? []).length,
                              ),
                            ),
                          ),
                          SliverToBoxAdapter(
                            child: SizedBox(
                              height: 16.w,
                            ),
                          )
                        ],
                      )))
            ],
          );
        }));
  }

  Widget _buildAppbar() {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.only(
          top: ScreenUtil().statusBarHeight, left: 16.w, right: 16.w),
      height: kToolbarHeight + ScreenUtil().statusBarHeight,
      child: Row(
        children: [
          AppUserManager().isLeader()
              ? GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () {
                    logic.openShareAndScreenshot(0);
                  },
                  child: Container(
                      // color: Colors.red,
                      // padding: EdgeInsets.only(left: 16.w),
                      alignment: Alignment.center,
                      child: Row(
                        children: [
                          AutoImage(
                            Assets.iconShare,
                            width: 16.w,
                          ),
                          4.horizontalSpace,
                          Text(
                            LocaleKeys.save.tr,
                            style: TextStyle(
                                fontSize: 12.sp,
                                fontWeight: FontWeight.w500,
                                color: AppColor.color181818),
                          )
                        ],
                      )),
                )
              : _buildAppLogo(),
          // leadingWidth: AppUserManager().isLeader() ? 100.w : 200.w,

          Expanded(
              child: _buildSearchButton().marginSymmetric(horizontal: 12.w)),
          Obx(() {
            return Visibility(
              visible: AppUserManager().isLogin,
              child: _buildCopyId(),
            );
          })
        ],
      ),
    );
  }

  // 添加搜索按钮组件
  Widget _buildSearchButton() {
    return GestureDetector(
      onTap: () {
        Get.toNamed(AppRoutes.searchPage);
      },
      child: Container(
        // margin: EdgeInsets.only(right: 12.w),
        padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.w),
        height: 36.w,
        decoration: BoxDecoration(
          color: AppColor.colorF5F5F5,
          borderRadius: BorderRadius.circular(18.w),
        ),
        child: Hero(
          tag: 'search_bar',
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(
                Icons.search,
                color: AppColor.color999999,
                size: 18.w,
              ),
              8.horizontalSpace,
              Text(
                LocaleKeys.search_placeholder.tr,
                style: TextStyle(
                  color: AppColor.color999999,
                  fontSize: 14.sp,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildCarouselSlider() {
    return (logic.homeModelRx.value.banner ?? []).isEmpty
        ? SizedBox(
            height: 180.w,
          )
        : Stack(
            children: [
              CarouselSlider.builder(
                itemCount: (logic.homeModelRx.value.banner ?? []).length,
                // carouselController: logic.carouselController,
                itemBuilder: (BuildContext context, int index, int realIndex) {
                  // Get.toNamed(AppRoutes.goodsInfoPage,
                  // arguments: {'id': homeList.id});
                  return GestureDetector(
                    onTap: () {
                      if (AppUserManager().isLogin) {
                        // Get.toNamed(AppRoutes.goodsInfoPage, arguments: {
                        //   'id': (logic.homeModelRx.value.banner ?? [])[index].id
                        // });
                      } else {
                        Get.toNamed(AppRoutes.login);
                      }
                    },
                    child: ImageView(
                      imageUrl:
                          (logic.homeModelRx.value.banner ?? [])[index].img,
                      width: 1.sw,
                      height: 180.w,
                      borderRadius: BorderRadius.circular(16.w),
                    ),
                  );
                },
                options: CarouselOptions(
                  height: 180.w,
                  viewportFraction: 1,
                  // enlargeFactor: 0,
                  enlargeCenterPage: true,
                  // initialPage: logic.currentPlayRx.value,
                  enableInfiniteScroll: true,
                  autoPlay: true,
                  autoPlayInterval: Duration(seconds: 3),
                  autoPlayAnimationDuration: Duration(milliseconds: 800),
                  autoPlayCurve: Curves.fastOutSlowIn,
                  onPageChanged: (int count, CarouselPageChangedReason reason) {
                    logic.carouselIndex.value = count;
                    // logic.changePlayPodcast(count);
                    // clog('onPageChanged   $count  reason  ${reason.name}  ');
                  },
                ),
              ),
              Positioned(
                bottom: 12.w,
                // left: 0,

                right: 12.w,
                child: Container(
                  padding: EdgeInsets.symmetric(vertical: 8.w),
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                      colors: [
                        Colors.transparent,
                        Colors.black.withOpacity(0.3),
                      ],
                    ),
                    borderRadius: BorderRadius.only(
                      bottomLeft: Radius.circular(16.w),
                      bottomRight: Radius.circular(16.w),
                    ),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: List.generate(
                      (logic.homeModelRx.value.banner ?? []).length,
                      (index) => Obx(() {
                        bool isSelected = logic.carouselIndex.value == index;
                        return Container(
                          width: isSelected ? 16.w : 8.w,
                          height: 4.w,
                          margin: EdgeInsets.symmetric(horizontal: 2.w),
                          decoration: BoxDecoration(
                            color: isSelected
                                ? Colors.white
                                : Colors.white.withOpacity(0.4),
                            borderRadius: BorderRadius.circular(2.w),
                          ),
                        );
                      }),
                    ),
                  ),
                ),
              ),
            ],
          );
  }

  Widget _buildAppLogo() {
    return Container(
      padding: EdgeInsets.only(left: 16.w),
      alignment: Alignment.centerLeft,
      child: Row(
        children: [
          AutoImage(
            Assets.appLogo,
            width: 24.w,
          ),
          8.horizontalSpace,
          Text(
            LocaleKeys.bf_home.tr,
            style: TextStyle(
                fontSize: 16.sp,
                fontWeight: FontWeight.w500,
                color: AppColor.color181818),
          )
        ],
      ),
    );
  }

  Widget _buildCopyId() {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        if (AppUserManager().isLogin) {
          logic.copyId();
        } else {
          Get.toNamed(AppRoutes.login);
        }
      },
      child: Text(
        LocaleKeys.member_id.tr,
        style: TextStyle(
            fontSize: 14.sp,
            fontWeight: FontWeight.w500,
            color: AppColor.color282828),
      ),
    );
  }

// Widget _buildSc() {
//   return Screenshot(
//     controller: screenshotController,
//     child: Container(
//       color: Colors.white,
//       child: Column(
//         mainAxisSize: MainAxisSize.min,
//         children: [
//           ImageView(
//             imageUrl: widget.img,
//             width: 330.w,
//             height: 330.w,
//           ),
//           Padding(
//             padding: EdgeInsets.symmetric(horizontal: 16.w),
//             child: Column(
//               crossAxisAlignment: CrossAxisAlignment.start,
//               children: [
//                 Text(
//                   widget.title,
//                   maxLines: 2,
//                   overflow: TextOverflow.ellipsis,
//                   style: TextStyle(
//                       color: AppColor.color282828,
//                       fontSize: 14.sp,
//                       fontWeight: FontWeight.w500),
//                 ),
//                 8.verticalSpaceFromWidth,
//                 Text(
//                   "${LocaleKeys.agent_code.tr}: $uid",
//                   style: TextStyle(
//                       color: AppColor.color282828,
//                       fontSize: 14.sp,
//                       fontWeight: FontWeight.w500),
//                 ),
//                 8.verticalSpaceFromWidth,
//                 Text(
//                   "${LocaleKeys.agent_contact.tr}: $agentPhone",
//                   style: TextStyle(
//                       color: AppColor.color282828,
//                       fontSize: 14.sp,
//                       fontWeight: FontWeight.w500),
//                 ),
//                 8.verticalSpaceFromWidth,
//                 Text(
//                   "${LocaleKeys.price.tr}: $formattedPrice",
//                   style: TextStyle(
//                       color: AppColor.primary,
//                       fontSize: 14.sp,
//                       fontWeight: FontWeight.w500),
//                 ),
//               ],
//             ),
//           ),
//           12.verticalSpaceFromWidth,
//         ],
//       ),
//     ),
//   );
// }
}
